﻿using System;
using System.Threading.Tasks;
using BASIC_CORE.Domain.Caching.Repositories;
using BASIC_CORE.Storage.Caching.DBContext;
using ServiceStack;

namespace BASIC_CORE.Storage.Caching.Repositories
{
    public class DistributeLockCacheRepository : IDistributeLockCacheRepository
    {
        private RedisDbContext _redisDb;
        public DistributeLockCacheRepository(RedisDbContext redisDbContext)
        {
            _redisDb = redisDbContext;
        }

        public object GetObject(string lockId)
        {
            using var redisClient = Task.FromResult(_redisDb.GetRedisClient()).Result.Result;
            var obj = redisClient.GetValue(lockId);
            return obj;
        }

        public bool IsExistLockedId(string lockId)
        {
            using var redisClient = Task.FromResult(_redisDb.GetRedisClient()).Result.Result;
            var obj = redisClient.GetValue(lockId);
            return obj.IsNullOrEmpty() ? true : false;
        }

        public void RemoveLockedId(string lockId)
        {
            using var redisClient = Task.FromResult(_redisDb.GetRedisClient()).Result.Result;
            redisClient.Remove(lockId);
        }

        public void SetLockedId(string lockId)
        {
            using var redisClient = Task.FromResult(_redisDb.GetRedisClient()).Result.Result;
            redisClient.Set(lockId, lockId);
        }

        public void SetLockedId(string lockId, TimeSpan timeSpan)
        {
            using var redisClient = Task.FromResult(_redisDb.GetRedisClient()).Result.Result;
            redisClient.Set(lockId, lockId, timeSpan);
        }
    }
}
